from django.db import models
from django.contrib.auth.models import User
from article.models import ArticlePost
# django-ckeditor_5 富文本编辑器
from django_ckeditor_5.fields import CKEditor5Field
from mptt.models import MPTTModel, TreeForeignKey

# 博文的评论
class Comment(MPTTModel):
    # 外键article被评论的文章
    article = models.ForeignKey(
        ArticlePost,
        on_delete=models.CASCADE,
        related_name='comments'
    )
    # user是评论者
    user = models.ForeignKey(
        User, 
        on_delete=models.CASCADE, 
        related_name='comments'
    )
    # body = models.TextField()
    #使用富文本编辑器
    body = CKEditor5Field()
    created = models.DateTimeField(auto_now_add=True)
    # 新增，mptt树形结构
    parent = TreeForeignKey(
        'self',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='children'
    )

    # 新增，记录二级评论回复给谁, str
    reply_to = models.ForeignKey(
        User,
        null=True,
        blank=True,
        on_delete=models.CASCADE,
        related_name='replyers'
    )
        # 替换 Meta 为 MPTTMeta
    # class Meta:
    #     ordering = ('created',)
    class MPTTMeta:
        order_insertion_by = ['created']
        
    def __str__(self):
        return self.body[:20]
    

#留言
class Notification(models.Model):
    recipient = models.ForeignKey(User, on_delete=models.CASCADE)  # 接收通知的用户
    actor = models.ForeignKey(User, related_name='notifications', on_delete=models.CASCADE)  # 发送通知的用户
    verb = models.CharField(max_length=255)  # 动词短语
    target = models.ForeignKey('article.ArticlePost', on_delete=models.CASCADE)  # 目标文章
    action_object = models.ForeignKey('comment.Comment', null=True, blank=True, on_delete=models.CASCADE)  # 动作对象
    created_at = models.DateTimeField(auto_now_add=True)  # 创建时间
    is_read = models.BooleanField(default=False)  # 是否已读

    def __str__(self):
        return f'Notification for {self.recipient.username} from {self.actor.username}'